package com.cos.utils;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;

@Component
public class OidUtils {

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     *
     * @Author lyc
     * @Description: 订单id的规则:时间+用户id的后四位+流水号
     * @Return:
     * @Create: 21/07/21 08:45
     *
     */
    public  String createOrderId(Integer uid){
        StringBuffer buffer=new StringBuffer();
        //时间
        String dateFormat = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //随机数
        String random = RandomStringUtils.random(5, false, true);
        //用户id后四位
        String isStr=lastUid(uid);
        //流水号(不能重复)
        Long orderIndex = redisTemplate.opsForValue().increment("order-index");
        buffer.append(dateFormat).append(random).append(isStr).append(orderIndex);
        return buffer.toString();

    }
    //如果用户id不足四位需要补零
    public String lastUid(Integer uid){
        StringBuffer stringBuffer=new StringBuffer();
        String s=uid.toString();
        if (s.length()<4) {
            stringBuffer.append(uid);
            for (int i = 0; i < 4-s.length(); i++) {
                stringBuffer.insert(0,"0");
            }
        }else {
            stringBuffer.append(s.substring(s.length()-4));
        }
        return stringBuffer.toString();
    }

    public static void main(String[] args) {
        OidUtils oidUtils = new OidUtils();
        
        String orderId = oidUtils.lastUid(42);
        System.out.println(orderId);
    }

}
